
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.*;
import java.util.*;

public class DocxTest {
    private static String inputUrl = "/Users/wsj/Desktop/word/111.docx";
    private static String outputUrl = "/Users/wsj/Desktop/word/222.docx";
    public static void main(String[] args) {
        Map<String, String> testMap = new HashMap<String, String>();
        testMap.put("name", "张三");
        testMap.put("idno", "422123762173612683412");
        changeWord(inputUrl,outputUrl,testMap);

    }

    private static void changeWord(String inputUrl, String outputUrl, Map<String, String> testMap) {
        //模板转换默认成功
        boolean chaneFlag = true;
        try {
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
            changeFlagText(document,testMap);
            File file = new File(outputUrl);
            FileOutputStream stream = new FileOutputStream(file);
            document.write(stream);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void changeFlagText(XWPFDocument document, Map<String, String> testMap) {
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs){
            //判断此段落是否需要进行转换
            String text = paragraph.getText();
            if(check(text)){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run:runs){
                    //替换模板原来位置
                    run.setText(ChangeValue(run.toString(),testMap),0);
                }

            }

        }

    }

    private static String ChangeValue(String value,Map<String, String> testMap) {
        Set<Map.Entry<String, String>> textSets = testMap.entrySet();
        for (Map.Entry<String, String> textSet:textSets){
            String key = "${"+textSet.getKey()+"}";
            if(value.indexOf(key)!= -1){
                value = textSet.getValue();
            }
        }
        //模板未匹配到区域替换为空
        if(check(value)){
            value = "";
        }
        return value;
    }

    private static boolean check(String text) {
        boolean check = false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;
    }

}
